

#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "nvs_flash.h"
#include "esp_system.h"
#include "esp_chip_info.h"
#include "esp_psram.h"
#include "esp_flash.h"
#include <stdio.h>
#include <string.h>
#include "led.h"
#include "exit.h"
#include "uart.h"
#include "esptim.h"
#include "gptim.h"
#include "wdt.h"
#include "swpwm.h"
#include "hwpwm.h"
#include "xl9555.h"
#include "24cxx.h"
#include "OLED.h"
#include "spilcd.h"
#include "esp_rtc.h"
#include "adc1.h"
#include "ap3216c.h"
#include "sensor.h"
#include "dht11.h"
#include "rng.h"
#include "qma6100p.h"
/**
 * @brief       显示原始数据
 * @param       x, y : 坐标
 * @param       title: 标题
 * @param       val  : 值
 * @retval      无
 */
void user_show_mag(uint16_t x, uint16_t y, char *title, float val)
{
    char buf[20];

    sprintf(buf,"%s%3.1f", title, val);                 /* 格式化输出 */
    lcd_fill(x + 30, y + 16, x + 160, y + 16, WHITE);   /* 清除上次数据(最多显示20个字符,20*8=160) */
    lcd_show_string(x, y, buf,BLACK, BLUE,16,0);      /* 显示字符串 */
}

/**********************************
 * @brief       程序入口
 * @param       无
 * @retval      无
 ***********************************/
i2c_obj_t i2c0_master;

void app_main(void)
{
    esp_err_t ret;
    uint8_t t;
    qma6100p_rawdata_t xyz_rawdata;
    ret = nvs_flash_init();                                         /* 初始化NVS */
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
    {
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }
    
    LED_init();
    usart_init(115200); 
    i2c0_master = iic_init(I2C_NUM_0);  /* 初始化IIC0 */
    spi2_init();                        /* 初始化SPI2 */
    xl9555_init(i2c0_master);           /* IO扩展芯片初始化 spi上扩展端口要用*/
    lcd_init();                         /* 初始化LCD */
    qma6100p_init(i2c0_master);         /* 初始化三轴加速度计 */
    

    lcd_clear(WHITE);

    lcd_show_string(30,90,"QMA6100P TEST",BLACK,GREEN,16,0); 
    lcd_show_string(30,110,"ACC_X:",BLACK,GREEN,16,0); 
    lcd_show_string(30,130,"ACC_Y:",BLACK,GREEN,16,0); 
    lcd_show_string(30,150,"ACC_Z:",BLACK,GREEN,16,0); 
    lcd_show_string(30,170,"Pitchitch:",BLACK,GREEN,16,0); 
    lcd_show_string(30,190,"Roll:",BLACK,GREEN,16,0); 
    while(1)
    {
        vTaskDelay(10);
        t++;

        if (t == 20)                    /* 0.2秒左右更新一次三轴原始值 */
        {   
            qma6100p_read_rawdata(&xyz_rawdata);
            
            user_show_mag(30, 110, "ACC_X :", xyz_rawdata.acc_x);
            user_show_mag(30, 130, "ACC_Y :", xyz_rawdata.acc_y);
            user_show_mag(30, 150, "ACC_Z :", xyz_rawdata.acc_z);
            user_show_mag(30, 170, "Pitch :", xyz_rawdata.pitch);
            user_show_mag(30, 190, "Roll  :", xyz_rawdata.roll);
            
            t = 0;
            LED_TOGGLE();
        }
        
    }
}

//lcd_show_num(30 + 40, 130, temperature, 2,YELLOW,GRAY,16);   /* 显示温度 */
//lcd_show_string(30,150,"Humi:  %",BLACK,GREEN,16,0); 